// import notification from 'ant-design-vue/es/notification'
import { formatTimeInObj } from '@/utils/timeFixer'
import $get from 'lodash.get'

const Cookie = process.client ? require('js-cookie') : undefined

export default function ({ app, $axios, redirect }) {
  // 基本配置
  $axios.defaults.timeout = 300000
  $axios.defaults.retry = 3
  $axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

  $axios.onRequest(config => {
    console.log('Making request to ' + config.url)
  })

  $axios.onResponse(resp => {
    if (resp && resp.config && resp.config.url && resp.config.url.includes('authless/login')) {
      if (resp.data && resp.data.refresh_token) {
        Cookie.set('refresh_token', resp.data.refresh_token)
      }
    }
    const code = $get(resp, 'data.code', -1)

    if (code === '100011') {
      if (resp && resp.config && resp.config.url && resp.config.url.includes('paperRead/isPermission')) return false
      // process.client && notification.error({ message })
    } else if (code === '040005') {
      return app.$auth.logout('local')
    } else if (code === '000000') {
      const respData = resp.data.data
      if (!respData) return false
      formatTimeInObj(respData)
    }
  })

  $axios.onError(error => {
    const res = error.response
    const code = parseInt(res && res.status)
    const config = error.config

    if (code === 401) {
      if (config && config.url && config.url.includes('auth/logout')) return false
      else if (Cookie.get('rememberMe') && !config.url.includes('auth/profile') && config.client) {
        $axios({
          method: 'POST',
          url: '/authless/login',
          params: {
            grant_type: 'refresh_token',
            refresh_token: Cookie.get('refresh_token')
          },
          auth: { username: 'test_client', password: 'test_secret' },
          headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).then(res => {
          Cookie.set('refresh_token', res.data.refresh_token)
          app.$auth.setUserToken(res.data.access_token)
            .then(() => console.log('User set!'))
          // Set the variable for keeping track of the retry count
          config.__retryCount = config.__retryCount || 0

          // Check if we've maxed out the total number of retries
          if (config.__retryCount >= config.retry) {
            // Reject with the error
            return Promise.reject(error)
          }

          // Increase the retry count
          config.__retryCount += 1
          var backoff = new Promise(function (resolve) {
            setTimeout(function () {
              resolve()
            }, 1000)
          })
          backoff.then(function () {
            config.headers.Authorization = 'Bearer ' + res.data.access_token
            if (app.router.history.current.name === 'index') {
              app.router.history.go(-1)
              // process.client && notification.success({ message: '登录超时，正在重新登录' })
            } else {
              // process.client && notification.success({ message: '登录凭证过期，正在重新登录' })
            }
            return $axios(config)
          })
        })
      } else {
        app.$auth.logout('local').then(() => {
          // process.client && notification.success({ message: '登录凭证过期，请重新登录' })
        })
      }
    } else if (code === 400) {
      if (config && config.url && /login|logout/.test(config.url)) {
        if (/logout/.test(config.url)) {
          app.router.push('/users/login')
        }
      } else if (res && res.data && res.data.code === '040005') {
        app.$auth.logout('local').then(() => {
          // process.client && notification.success({ message: res.data.mesg || '登录凭证已失效，请重新登录' })
        })
      }
    } else if (/500|504/.test(code)) {
      // 去除获取用户信息的报错
      if (config && /profile/.test(config.url)) {
        // process.client && notification.error({ message: '无法获取用户信息' })
      }
    } else {
      // process.client && notification.error({ message: '请稍后再试' })
    }
  })
}
